enum CacheType {
  Local,
  Session
}

class Cache {
  storage: Storage

  constructor(type: CacheType) {
    this.storage = type === CacheType.Local ? localStorage : sessionStorage
  }

  /**
   * 设置浏览器/session缓存
   * @param key
   * @param value
   */
  setCache(key: string, value: any) {
    if (value) {
      this.storage.setItem(key, JSON.stringify(value))
    }
  }

  /**
   * 通过key获取到缓存的值
   * @param key
   */
  getCache(key: string) {
    const value = this.storage.getItem(key)
    if (value) {
      return JSON.parse(value)
    }
  }

  /**
   * 通过key清除缓存
   * @param key
   */
  removeCache(key: string) {
    this.storage.removeItem(key)
  }

  /**
   * 清理所有的缓存值
   */
  clear() {
    this.storage.clear()
  }
}

const localCache = new Cache(CacheType.Local)
const sessionCache = new Cache(CacheType.Session)

export { localCache, sessionCache }
